import { UploadRawFile } from 'element-plus'
import * as xlsx from 'xlsx'
import { WorkBook } from 'xlsx'
/**
 * @description: 读取excel文件并返回数据
 * @param {function} 回调函数参数data,dataRef,一个是数据，一个是exce表单的索引
 * @return:
 */
export const readExcel = async (file: UploadRawFile | undefined): Promise<unknown[]> => {
  if (!file) {
    return []
  }
  const dataBinary = await new Promise(resolve => {
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = ev => {
      resolve(ev.target!.result)
    }
  })
  let workBook = xlsx.read(dataBinary, { type: 'binary', cellDates: true })
  let workSheet = workBook.Sheets[workBook.SheetNames[0]]
  const data = xlsx.utils.sheet_to_json(workSheet)
  return data
}

/**
 * @description: 导出excel文件并返回数据
 * @param {function} 回调函数参数data,dataRef,一个是数据，一个是exce表单的索引
 * @return:
 */

export function exportExcelFile(array: unknown[], fileName = 'example.xlsx', sheetName = '表1') {
  const jsonWorkSheet = xlsx.utils.json_to_sheet(array)
  const workBook: WorkBook = {
    SheetNames: [sheetName],
    Sheets: {
      [sheetName]: jsonWorkSheet
    }
  }
  return xlsx.writeFile(workBook, fileName)
}
